// pages/home/home.js
const DB=wx.cloud.database().collection("dataList");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeList:[],// 显示的条目
    money:[// 分类的类别
      ['全部','只显示随礼','只显示收礼'],
      ['全部','只显示礼金','只显示礼品']
    ],
    indexArray:[0,0],
    classifyA:'全部',
    classifyB:'全部',
    isCheckShow:false,
    allCheck:false,
    numSum:0,
    showSearch:false,
    searchIsfocus:false,
    animationData:{},
    animationTop:{},
    animationBottom:{},
    isshadow:true,
    tips:[],// 防骗知识
    totalCount:0,// 总记录数
    page:1,// 当前页码
    perNum:10, //每页显示的条目数量
    maxPage:0, // 总页数
    isTouchBottom:false, //数据是否触底了
  },

  /**
   * 长按事件
   */
  editList(e){
    const that=this;
    wx.showActionSheet({
      alertText:'关于“'+e.currentTarget.dataset.user+'”的记录',
      itemList:['编辑','删除'],
      itemColor:'#5EC2F6',
      success(res){
        if(res.tapIndex==0){
          wx.navigateTo({
            url: '/pages/edit/edit?id='+e.currentTarget.dataset.id
          })
        }else{
          wx.showModal({
            title:'删除记录',
            content:'确定删除？',
            success (res) {
              if (res.confirm) {
                wx.showLoading({
                  title: '删除中...',
                })
                DB.doc(e.currentTarget.dataset.id).remove({
                  success(rem){
                    wx.hideLoading();
                    that.reload();
                    wx.showToast({
                      title: '删除成功'
                    })
                  },
                  fail(){
                    wx.hideLoading();
                    wx.showToast({
                      title: '删除失败',
                      icon:'error'
                    })
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  },
  /**
   * 搜索框提交内容
   * @param {*} e 
   */
  handlesearch(e){
    const that=this;
    if(e.detail.value==''){
      that.handleblur();
      // this.setData({
      //   showSearch:false,
      //   searchIsfocus:false
      // })
    }else{
      wx.navigateTo({
        url: '/pages/search/search?content='+e.detail.value,
        success(ret){
          that.setData({
            showSearch:false,
            searchIsfocus:false
          })
        }
      })
    }
  },

  /**
   * 使搜索框显示
   */
  showSearch(){
    var animation=wx.createAnimation({
      duration: 500,
      timingFunction: 'linear'
    })
    this.animation=animation;
    animation.width('100%').step();
    this.setData({
      animationData:animation.export()
    })
    setTimeout(function() {
      this.setData({
        showSearch:true,
        searchIsfocus:true
      })
    }.bind(this), 500)
  },

  /**
   * 搜索框失去焦点事件
   */
  handleblur(){
    // this.setData({
    //   showSearch:false,
    //   searchIsfocus:false
    // })
    var animation=wx.createAnimation({
      duration: 500,
      timingFunction: 'linear'
    })
    this.animation=animation;
    animation.width('130rpx').step();
    this.setData({
      animationData:animation.export()
    })
    
    setTimeout(function() {
      this.setData({
        showSearch:false,
        searchIsfocus:false
      })
    }.bind(this), 500)

  },

  /**监听用户转发小程序 */
  onShareAppMessage(e){
      return {
        title: '一个帮你记录上礼的小程序',
        path: "/pages/home/home",
        imageUrl:'http://ww1.sinaimg.cn/large/008cZqs9ly1gq68wok6g3j30dw0b4gqt.jpg'
      }
  },

  onShareTimeline(){
      return{
        title: '一个帮你记录上礼的小程序',
        path: "/pages/home/home"
      }
  },

  /**跳转发布 */
  handleIssue(){
    wx.navigateTo({
      url:'/pages/issue/issue'
    })
  },

  /**选择分类后触发 */
  handlePicker(e){
    wx.showLoading({
      title: '正在加载...',
    })
    this.setData({
      classifyA:this.data.money[0][e.detail.value[0]],
      classifyB:this.data.money[1][e.detail.value[1]],
      activeList:[],
      page:1
    })
    

    this.reload();
  },

  /**管理礼单 */
  handleEdit(){
    this.setData({
      isCheckShow:!(this.data.isCheckShow)
    })
    this.loadData();
  },

  /**复选框 */
  handleItem(e){
    let id=e.currentTarget.dataset.id;
    let {activeList}=this.data;
    let index=activeList.findIndex(v=>v._id===id);
    activeList[index].cheked=!activeList[index].cheked;
    
    let allCheck=false;
    let numSum=0;
    
    activeList.forEach(e => {
      if(e.cheked){
          numSum+=1;
      }else{
        allCheck=false;
      }
    })
    //判断购物车数组长度是不是空的
    allCheck=activeList.length?activeList.every(v=>v.cheked):false;
    allCheck=activeList.length?allCheck:false;
    
    this.setData({
      activeList:activeList,
      allCheck:allCheck,
      numSum:numSum
    })
  },

  /**点击全选 */
  handleAll(){
    let {allCheck}=this.data;
    let {activeList}=this.data;
    allCheck=!allCheck;
    activeList.forEach(e => {
      e.cheked=allCheck
    })
    let numSum=0;
    activeList.forEach(e => {
      if(e.cheked){
          numSum+=1;
      }else{
        allCheck=false;
      }
    })
    this.setData({
      allCheck:allCheck,
      activeList:activeList,
      numSum:numSum
    })
  },

  /**删除选中 */
  delAll(){
    wx.showLoading({
      title: '删除选中',
    })
    const that =this;
    let {activeList}=this.data;

    // 将选中的放到一个数组，并且更新本地的数据
    let delArr=[];
    for(let i=0;activeList[i]!=undefined;){
      if(activeList[i].cheked){
        delArr.push(activeList[i]._id);
        activeList.splice(i,1);
      }else{
        i=i+1;
      }
    }

    wx.cloud.callFunction({
      name:'delAll',
      data:{
        arr:delArr
      },
      success(ret){
        // console.log(ret);
        that.setData({
          activeList:activeList
        })
        that.loadData();
        wx.hideLoading();
        wx.showToast({
          title: '删除'+ret.result.stats.removed+'条',
        })
        
      },
      fail(e){
        wx.hideLoading();
        wx.showToast({
          title: '删除失败',
          icon:'error'
        })
        console.log("调用失败"+e);
      }
    })
  },

  /**重新根据本地数据加载显示是否全选和选中多少条 */
  loadData(){
    const {activeList}=this.data;
    let numSum=0;
    let allCheck=false;
    activeList.forEach(e => {
      if(e.cheked){
          numSum+=1;
      }
    })
    if(numSum==activeList.length){
      allCheck=true;
    }
    this.setData({
      allCheck:allCheck,
      numSum:numSum
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // const ontake=wx.getStorageSync('ontake');
    // if()
    const tips=wx.getStorageSync('tips');
    this.setData({
      tips:tips
    })
    this.reload();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.reload();
  },

  /**重新加载当前页面数据 */
  reload(){
    
    wx.showLoading({
      title: '加载中',
    })
    const openid=wx.getStorageSync('openid');
    const that=this;
    // 构建分类条件
    let man='.*';let way='.*';
    if(this.data.classifyA=='只显示随礼'){
      man='give'
    }else if(this.data.classifyA=='只显示收礼'){
      man='return'
    }
    if(this.data.classifyB=='只显示礼金'){
      way='money'
    }else if(this.data.classifyB=='只显示礼品'){
      way='goods'
    }

    // 构建请求所有数据的参数
    let param={
      _openid:openid,
      man:{
          $regex:man,
          $options:'i'
      },
      way:{
          $regex:way,
          $options:'i'
      },
    }

    this.getAllData(param);
    this.getCount();
  },

  /**查询所有 符合要求 的数据 */
  getAllData(param){
    const that=this;
    wx.cloud.callFunction({
      name:'gePage',
      data:param
    }).then(res=>{
      let dataList=res.result.data
      dataList.sort((a,b)=>b.date.localeCompare(a.date))
      wx.setStorageSync('dataList', dataList)
      
      // 计算总数和总页数
      let maxPage=(dataList.length)/(that.data.perNum)
      if(((dataList.length) % (that.data.perNum))!=0){
        maxPage+=1
      }
      if(dataList.length<that.data.perNum || dataList.length==that.data.perNum){
        maxPage=1
      }
      that.setData({
        totalCount:dataList.length,
        maxPage:maxPage
      })

      that.toPage();
    })
  },

  // 计算支出收入金额
  getCount(){
    let dataList=wx.getStorageSync('dataList');
    let moneyCountPay=0;// 支出金额
    let moneyCountIncome=0;// 收入金额
    dataList.forEach((item)=>{
      if(item.way=='money'){
        if(item.man=='give'){
          moneyCountPay+=parseInt(item.gift)
        }else{
          moneyCountIncome+=parseInt(item.gift)
        }
      }
    })
    let {tips}=this.data
    tips.push({
      top:'当前页面金额统计',
      bottom:'支出:'+moneyCountPay+'元,收入:'+moneyCountIncome+'元'
    })
    this.setData({
      tips:tips
    })

  },
  /**
   * 翻页
   * 需要提前设置data属性page和perNum
   */
  toPage(){
    let {page,perNum,activeList}=this.data
    let dataList=wx.getStorageSync('dataList');
    activeList=[];
    for(let i=0;i<(page*perNum) && i<dataList.length;i++){
      activeList.push(dataList[i]);
    }
    this.setData({
      activeList:activeList
    })
    wx.hideLoading();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
      wx.showLoading({
        title: '加载中',
      })
      let dataList=wx.getStorageSync('dataList');

      if(this.data.page+1==this.data.maxPage || this.data.page==this.data.maxPage){
        this.setData({
          isTouchBottom:true,
          activeList:dataList
        })
        wx.hideLoading();
      }else{
        this.setData({
          page:this.data.page+1
        })
        this.toPage();
      }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(){
    return {
      title: '一个帮你记录上礼的小程序',
      path: "pages/home/home",
      imageUrl:'http://ww1.sinaimg.cn/large/008cZqs9ly1gq68wok6g3j30dw0b4gqt.jpg'
    }
  },
  onShareTimeline(){
    return{
      title: '一个帮你记录上礼的小程序',
      path: "/pages/home/home"
    }
  },

  /**点击打开遮罩层 */
  open(){
    var animation=wx.createAnimation({
      duration: 2000,
      timingFunction: 'linear'
    })
    this.animation=animation;
    animation.top('-100vh').step();

    var animation1=wx.createAnimation({
      duration: 2000,
      timingFunction: 'linear'
    })
    this.animation=animation1;
    animation1.bottom('-100vh').step();

    this.setData({
      animationTop:animation.export(),
      animationBottom:animation1.export()
    })
    setTimeout(function() {
      this.setData({
        isshadow:false
      })
      wx.showTabBar({
        animation: true,
      })
    }.bind(this), 1500)
  },

    /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const that=this;
    wx.hideTabBar();
    const DD=wx.cloud.database().collection("content");
    DD.doc("2").get({
      success(res){
        wx.setStorageSync('tips', res.data.content);
        that.setData({
          tips:res.data.content
        })
      }
    })
    setTimeout(function(){
      that.open();
    },3000);
  },
})